<?php
namespace app\admin\controller;
use app\common\model\Navigation as NavigationModel;
use app\common\model\Permission;
use think\Loader;
use think\Request;

class Navigation extends Base{

    public function index(){
        $this->data['model'] = $this->data['navigation'];
        $this->data['column'] = $this->column();
        $this->data['title'] = "导航管理";
        return view('',$this->data);
    }


    public function add(){
        $this->data['title'] = '栏目添加';
        $this->getPermission();
        $this->getFirstLevel();
        return view('',$this->data);
    }


    public function edit(Request $request){
        $this->data['title'] = '栏目更新';
        $this->getPermission();
        $this->getFirstLevel();

        $this->data['model'] = NavigationModel::get($request->param('id'));

        return view('',$this->data);
    }


    public function handle(Request $request){

        $data = $request->post();
        $data['url'] = url($data['permission']);
        $validate = Loader::validate('Navigation');
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $data['op_user'] = $this->admin->id;
        if(empty($data['id'])){
            $data['add_time'] = $data['update_time'] = time();
            if(NavigationModel::create($data)){
                $this->success("新增成功");
            }
        }else{
            $data['update_time'] = time();
            $navigationModel = new NavigationModel();
            if($navigationModel -> save($data,['id'=>$data['id']])){
                $this->success("更新成功");
            }
        }

        $this->error("操作失败");
    }


    public function delete(Request $request){
        $model = NavigationModel::get($request->param('id'));
        if($model){
            if(NavigationModel::where(['pid'=>$model->id])->count()){
                $this->error("该栏目有子栏目，不能删除。");
            }
            $res = $model ->delete();
            if($res){
                $this->success("删除成功");
            }
        }

        $this->error("操作失败");
    }


    /**
     * 这样写是为了语义 下同
     */
    protected function getPermission(){
        $this->data['permission'] = Permission::where(['type'=>0])->select();
    }

    protected function getFirstLevel(){
        $this->data['firstLevel'] = NavigationModel::where('pid',0)->select();
    }


    protected function column(){
        return [
            'title'=>'链接名称',
            'sort'=>'排序',
            'url'=>'链接地址',
        ];
    }

}